package com.xiaoyang.forum.common.interceptor;

import com.xiaoyang.forum.common.util.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //从 header 中获取 token
        String jwtToken = request.getHeader("token");
        log.info("获取路径:{}", request.getRequestURI());
        log.info("从header中获取token:{}", jwtToken);
        //验证用户 token
        Claims claims = JWTUtil.parseJWT(jwtToken);
        if (null == claims){
            response.setStatus(401);
            return false;
        }
        log.info("令牌验证通过, 放⾏");
        return true;
    }
}